<script lang="ts" setup>
import type { DressResourceApi } from '#/api/wedding/dressresource';

import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';

import { getDressResourcePage } from '#/api/wedding/dressresource';

import { Image, Spin, message, Button, Input, Select, Empty, Carousel } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

import { generateShareCode } from '#/utils/share-code';
import { getGlobalThemeConfig, mergeThemeConfig } from '#/utils/theme-defaults';

defineOptions({ name: 'DressGallery' });

const router = useRouter();
const loading = ref(true);
const dressList = ref<DressResourceApi.DressResource[]>([]);
const searchKeyword = ref('');
const selectedBrand = ref<string | undefined>(undefined);
const selectedColor = ref<string | undefined>(undefined);

// 全局主题配置（从 localStorage 获取用户设置的全局主题）
const globalThemeConfig = computed(() => {
  const config = getGlobalThemeConfig();
  console.log('全局主题配置:', config);
  return config;
});

// 头部样式
const headerStyle = computed(() => {
  const config = globalThemeConfig.value;
  
  // 构建背景样式
  let background = 'linear-gradient(to right, #ff1493, #9b30ff)'; // 默认渐变
  
  if (config.primaryColor && config.secondaryColor) {
    background = `linear-gradient(135deg, ${config.primaryColor}, ${config.secondaryColor})`;
  }
  
  const style: Record<string, string> = {
    background,
    backgroundSize: 'cover',
    backgroundPosition: 'center',
  };
  
  // 如果有背景图片，添加背景图片
  if (config.backgroundImage) {
    style.backgroundImage = `url(${config.backgroundImage})`;
  }
  
  console.log('全局主题配置:', config);
  console.log('头部样式:', style);
  
  return style;
});

// 加载婚纱列表
async function loadDressList() {
  try {
    loading.value = true;
    const params = {
      pageNo: 1,
      pageSize: 100, // 加载更多数据
      status: 'available', // 只显示可用的婚纱
    };
    
    const result = await getDressResourcePage(params);
    dressList.value = result.list || [];
  } catch (error) {
    message.error('加载婚纱列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
}

// 筛选后的婚纱列表
const filteredDressList = computed(() => {
  let list = dressList.value;
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    list = list.filter(dress => 
      dress.dressName?.toLowerCase().includes(keyword) ||
      dress.dressCode?.toLowerCase().includes(keyword) ||
      dress.brand?.toLowerCase().includes(keyword)
    );
  }
  
  // 品牌筛选
  if (selectedBrand.value) {
    list = list.filter(dress => dress.brand === selectedBrand.value);
  }
  
  // 颜色筛选
  if (selectedColor.value) {
    list = list.filter(dress => dress.color === selectedColor.value);
  }
  
  return list;
});

// 获取所有品牌
const brands = computed(() => {
  const brandSet = new Set(dressList.value.map(dress => dress.brand).filter(Boolean));
  return Array.from(brandSet);
});

// 获取所有颜色
const colors = computed(() => {
  const colorSet = new Set(dressList.value.map(dress => dress.color).filter(Boolean));
  return Array.from(colorSet);
});

// 查看婚纱详情
function viewDressDetail(dress: DressResourceApi.DressResource) {
  const shareCode = generateShareCode(dress.id);
  router.push(`/wedding/dress-preview/${shareCode}`);
}

// 清除筛选
function clearFilters() {
  searchKeyword.value = '';
  selectedBrand.value = undefined;
  selectedColor.value = undefined;
}

onMounted(() => {
  loadDressList();
});
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 头部 -->
    <div 
      class="text-white" 
      :style="headerStyle"
    >
      <div class="max-w-7xl mx-auto px-4 py-6">
        <h1 class="text-3xl font-bold text-center mb-2">婚纱精选</h1>
        <p class="text-center opacity-90">选择您心仪的婚纱款式</p>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="sticky top-0 z-10 bg-white shadow-md">
      <div class="max-w-7xl mx-auto px-4 py-4">
        <div class="flex flex-col md:flex-row gap-3">
          <!-- 搜索框 -->
          <Input
            v-model:value="searchKeyword"
            placeholder="搜索婚纱名称、编码、品牌..."
            size="large"
            class="flex-1"
          >
            <template #prefix>
              <IconifyIcon icon="lucide:search" />
            </template>
          </Input>
          
          <!-- 品牌筛选 -->
          <Select
            v-model:value="selectedBrand"
            placeholder="选择品牌"
            size="large"
            class="w-full md:w-40"
            allow-clear
          >
            <Select.Option v-for="brand in brands" :key="brand" :value="brand">
              {{ brand }}
            </Select.Option>
          </Select>
          
          <!-- 颜色筛选 -->
          <Select
            v-model:value="selectedColor"
            placeholder="选择颜色"
            size="large"
            class="w-full md:w-40"
            allow-clear
          >
            <Select.Option v-for="color in colors" :key="color" :value="color">
              {{ color }}
            </Select.Option>
          </Select>
          
          <!-- 清除按钮 -->
          <Button 
            size="large" 
            @click="clearFilters"
            class="w-full md:w-auto"
          >
            清除筛选
          </Button>
        </div>
        
        <!-- 结果统计 -->
        <div class="mt-3 text-sm text-gray-600">
          共找到 <span class="font-semibold text-pink-600">{{ filteredDressList.length }}</span> 款婚纱
        </div>
      </div>
    </div>

    <!-- 婚纱列表 -->
    <div class="max-w-7xl mx-auto px-4 py-6">
      <Spin :spinning="loading" size="large">
        <div v-if="filteredDressList.length > 0" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          <div
            v-for="dress in filteredDressList"
            :key="dress.id"
            class="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition-shadow cursor-pointer dress-card"
          >
            <!-- 婚纱图片轮播 -->
            <div class="relative aspect-[3/4] bg-gray-100">
              <!-- 多图轮播 -->
              <Carousel
                v-if="dress.images && dress.images.length > 1"
                :autoplay="false"
                dots-class="custom-carousel-dots"
                class="h-full"
                @click.stop
              >
                <div
                  v-for="(image, index) in dress.images"
                  :key="index"
                  class="w-full h-full"
                >
                  <img
                    :src="image"
                    :alt="`${dress.dressName} - 图片${index + 1}`"
                    class="w-full h-full object-cover"
                    @click="viewDressDetail(dress)"
                  />
                </div>
              </Carousel>
              
              <!-- 单图显示 -->
              <img
                v-else-if="dress.images && dress.images.length === 1"
                :src="dress.images[0]"
                :alt="dress.dressName"
                class="w-full h-full object-cover"
                @click="viewDressDetail(dress)"
              />
              
              <!-- 无图片 -->
              <div 
                v-else 
                class="w-full h-full flex items-center justify-center text-gray-400"
                @click="viewDressDetail(dress)"
              >
                <IconifyIcon icon="lucide:image-off" class="text-6xl" />
              </div>
              
              <!-- 图片数量标签 -->
              <div 
                v-if="dress.images && dress.images.length > 1" 
                class="absolute top-2 left-2 px-2 py-1 rounded-full text-xs font-medium bg-black/60 text-white shadow-md flex items-center gap-1"
              >
                <IconifyIcon icon="lucide:images" class="text-sm" />
                {{ dress.images.length }}
              </div>
              
              <!-- 状态标签 -->
              <div class="absolute top-2 right-2">
                <span 
                  class="px-3 py-1 rounded-full text-xs font-medium bg-green-500 text-white shadow-md"
                >
                  可租赁
                </span>
              </div>
            </div>
            
            <!-- 婚纱信息 -->
            <div class="p-4">
              <h3 class="text-lg font-semibold text-gray-800 mb-2 truncate">
                {{ dress.dressName || '未命名婚纱' }}
              </h3>
              
              <div class="space-y-2 text-sm text-gray-600">
                <div class="flex items-center gap-2">
                  <IconifyIcon icon="lucide:tag" class="text-gray-400" />
                  <span>{{ dress.brand || '未设置品牌' }}</span>
                </div>
                
                <div class="flex items-center gap-2">
                  <IconifyIcon icon="lucide:palette" class="text-gray-400" />
                  <span>{{ dress.color || '未设置颜色' }}</span>
                </div>
                
                <div class="flex items-center gap-2">
                  <IconifyIcon icon="lucide:ruler" class="text-gray-400" />
                  <span>尺码: {{ dress.size || '均码' }}</span>
                </div>
              </div>
              
              <!-- 价格 -->
              <div class="mt-4 pt-4 border-t border-gray-100">
                <div class="flex items-baseline justify-between">
                  <div>
                    <span 
                      class="text-2xl font-bold" 
                      :style="{ color: (dress.mobileThemeConfig?.primaryColor || globalThemeConfig.primaryColor) || '#dc143c' }"
                    >
                      ¥{{ dress.rentalPrice || 0 }}
                    </span>
                    <span class="text-sm text-gray-500 ml-1">/天</span>
                  </div>
                  <Button 
                    type="primary" 
                    size="small"
                    :style="{ 
                      backgroundColor: (dress.mobileThemeConfig?.primaryColor || globalThemeConfig.primaryColor),
                      borderColor: (dress.mobileThemeConfig?.primaryColor || globalThemeConfig.primaryColor)
                    }"
                  >
                    查看详情
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <Empty
          v-else-if="!loading"
          description="暂无婚纱数据"
          class="my-16"
        >
          <Button type="primary" @click="clearFilters">
            清除筛选条件
          </Button>
        </Empty>
      </Spin>
    </div>

    <!-- 底部 -->
    <div class="bg-white border-t border-gray-200 mt-8">
      <div class="max-w-7xl mx-auto px-4 py-6 text-center">
        <p class="text-gray-600 mb-2">选择您心仪的婚纱，点击查看详情</p>
        <p class="text-gray-500 text-sm">© 2024 婚纱租赁管理系统</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 移动端优化 */
@media (max-width: 768px) {
  .max-w-7xl {
    max-width: 100%;
  }
}

/* 卡片悬停效果 */
.hover\:shadow-xl:hover {
  transform: translateY(-2px);
  transition: all 0.3s ease;
}

/* 图片加载效果 */
img {
  transition: transform 0.3s ease;
}

.dress-card:hover img {
  transform: scale(1.05);
}

/* 轮播图样式优化 */
:deep(.ant-carousel) {
  height: 100%;
}

:deep(.ant-carousel .slick-slider) {
  height: 100%;
}

:deep(.ant-carousel .slick-list) {
  height: 100%;
}

:deep(.ant-carousel .slick-track) {
  height: 100%;
}

:deep(.ant-carousel .slick-slide) {
  height: 100%;
}

:deep(.ant-carousel .slick-slide > div) {
  height: 100%;
}

/* 自定义轮播指示点样式 */
:deep(.custom-carousel-dots) {
  bottom: 8px !important;
}

:deep(.custom-carousel-dots li button) {
  background: rgba(255, 255, 255, 0.5) !important;
  width: 8px !important;
  height: 8px !important;
  border-radius: 50% !important;
}

:deep(.custom-carousel-dots li.slick-active button) {
  background: white !important;
  width: 24px !important;
  border-radius: 4px !important;
}

/* 轮播箭头样式 */
:deep(.ant-carousel .slick-prev),
:deep(.ant-carousel .slick-next) {
  color: white !important;
  font-size: 20px !important;
  z-index: 2 !important;
}

:deep(.ant-carousel .slick-prev) {
  left: 10px !important;
}

:deep(.ant-carousel .slick-next) {
  right: 10px !important;
}

:deep(.ant-carousel .slick-prev:hover),
:deep(.ant-carousel .slick-next:hover) {
  color: white !important;
  opacity: 1 !important;
}

/* 轮播箭头背景 */
:deep(.ant-carousel .slick-prev::before),
:deep(.ant-carousel .slick-next::before) {
  display: none;
}
</style>

